package cn.xlbweb.cli.service.impl;

import cn.xlbweb.cli.mapper.UserMapper;
import cn.xlbweb.cli.pojo.dto.UserInsertDTO;
import cn.xlbweb.cli.pojo.dto.UserListDTO;
import cn.xlbweb.cli.pojo.dto.UserUpdateDTO;
import cn.xlbweb.cli.service.UserService;
import cn.xlbweb.util.res.ResponseServer;
import cn.xlbweb.util.res.ResponseTable;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author: bobi
 * @date: 2019-02-11 16:02
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseServer getCurrentUser() {
        return null;
    }

    @Override
    public ResponseServer getUser(Integer id) {
        Map<String, Object> result = userMapper.getUser(id);
        if (!CollectionUtils.isEmpty(result)) {
            return ResponseServer.success(result);
        }
        return ResponseServer.error("用户不存在");
    }

    @Override
    public ResponseTable listUser(UserListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getSize());
        List<Map<String, Object>> results = userMapper.listUser(dto);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(results);
        return ResponseTable.success(pageInfo.getTotal(), results);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer insertUser(UserInsertDTO dto) {
        int count = userMapper.insertUser(dto);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("插入用户失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer updateUser(UserUpdateDTO dto) {
        int count = userMapper.updateUser(dto);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("更新用户失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer deleteUser(String ids) {
        int count = userMapper.deleteUser(ids);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("删除用户失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer resetPwd(String ids) {
        return null;
    }
}
